package com.zs.zuul.web;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AccessFilter extends ZuulFilter {

	@Override
	public String filterType() {	//前置过滤器
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;	//优先级,数字越大,优先级越低	对所有请求都会过滤
	}

	@Override
	public boolean shouldFilter() {
		return true;	//是否执行该过滤器	true代表需要过滤
	}

	@Override
	public Object run()  {
		//RequestContext 请求上下文	==> LocalThread
		RequestContext ctx = RequestContext.getCurrentContext();
		//获取请求对象
		HttpServletRequest request = ctx.getRequest();
		//获取请求对象传来的参数accessToken	令牌
		Object accessToken = request.getParameter("accessToken");
		if(accessToken == null){	//判断令牌是否为空
			System.out.println("access token is empty");
			//过滤该请求,不往下级服务去转发请求	到此结束
			ctx.setSendZuulResponse(false);
			//设置响应结果码
			ctx.setResponseStatusCode(401);
			//设置响应结果 json
			ctx.setResponseBody("{\"result\":\"accessToken is empty!\"}");

			//用cookie返回一个令牌
			//获取浏览器ip 计算一个令牌
			final String remoteHost = request.getRemoteHost();
			System.out.println("IP="+remoteHost);
			String mdencode = DigestUtils.md5DigestAsHex(remoteHost.getBytes());
			System.out.println("encode="+mdencode);
			Cookie cookie = new Cookie("accessToken",mdencode);
			HttpServletResponse response = ctx.getResponse();
			response.addCookie(cookie);
			return null;
		}else {
			//重新计算令牌
			final String remoteHost = request.getRemoteHost();
			System.out.println("IP="+remoteHost);
			String mdencode = DigestUtils.md5DigestAsHex(remoteHost.getBytes());
			System.out.println("encode="+mdencode);
			if(accessToken.equals(mdencode) == false){
				System.out.println("access token is error");
				//过滤该请求	不往下级服务去转发请求	到此结束
				ctx.setSendZuulResponse(false);
				//设置相应结果码
				ctx.setResponseStatusCode(401);
				ctx.setResponseBody("{\"result\":\"accessToken is error!\"}");
			}
		}
		//如果有token,则进行路由转发,这里turn的值没有意义,zuul框架没有使用该返回值
		return null;
	}
}
